import { saveFieldconfig, getFieldconfig } from '@/api/config';
import { debounce } from 'lodash-es';
/**
 * vxe-table 列配置持久化通用 Hook
 * @param tableId 唯一表格 ID
 * @param excludeFields 不参与配置的字段，默认 ['id', 'checkbox', 'operate']
 */
export function useVxeCustomConfig(tableId, excludeFields = ['id', 'checkbox', 'operate'], $modal) {
  // 查询服务端列配置
  const findCustomSetting = async (id) => {
    const res = await getFieldconfig(id);
    return JSON.parse(res.data.storedata || '{}');
  };
  // 保存服务端列配置（防抖）
  const saveCustomSetting = debounce(
    async (id, storeData) => {
      const res = await saveFieldconfig({
        storekey: id,
        storedata: storeData
      });
      if (res.code === 200 && $modal?.msgSuccess) {
        $modal.msgSuccess(res.msg);
      }
    },
    500,
    { leading: true, trailing: false }
  );

  // 返回 vxe-grid 使用的 custom-config 对象
  return {
    customConfig: {
      storage: true,
      restoreStore: () => findCustomSetting(tableId),
      updateStore: ({ storeData }) => saveCustomSetting(tableId, storeData),
      checkMethod: ({ column }) => column.field && !excludeFields.includes(column.field)
    }
  };
}
